package com.ruoyi.flowable.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.flowable.domain.App;
import com.ruoyi.flowable.domain.bo.BpmnConfigBo;
import com.ruoyi.flowable.domain.vo.AppVo;
import com.ruoyi.flowable.domain.vo.BpmnConfigVo;
import com.ruoyi.flowable.domain.vo.FormVersionVo;
import com.ruoyi.flowable.mapper.AppMapper;
import com.ruoyi.flowable.mapper.FormVersionMapper;
import com.ruoyi.flowable.service.IBpmnConfigService;
import com.ruoyi.flowable.utils.FlowableUtil;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Service;
import com.ruoyi.flowable.domain.bo.AppVersionBo;
import com.ruoyi.flowable.domain.vo.AppVersionVo;
import com.ruoyi.flowable.domain.AppVersion;
import com.ruoyi.flowable.mapper.AppVersionMapper;
import com.ruoyi.flowable.service.IAppVersionService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 事项版本Service业务层处理
 *
 * @author zxw
 * @date 2023-03-27
 */
@RequiredArgsConstructor
@Service
public class AppVersionServiceImpl implements IAppVersionService {

    private final AppVersionMapper baseMapper;
    private final AppMapper appMapper;
    private final FormVersionMapper formVersionMapper;

    private final FlowableUtil flowableUtil;
    private final IBpmnConfigService bpmnConfigService;

    /**
     * 查询事项版本
     */
    @Override
    public AppVersionVo queryById(Long versionId){
        return baseMapper.selectVoById(versionId);
    }

    /**
     * 查询事项版本列表
     */
    @Override
    public TableDataInfo<AppVersionVo> queryPageList(AppVersionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppVersion> lqw = buildQueryWrapper(bo);
        Page<AppVersionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询事项版本列表
     */
    @Override
    public List<AppVersionVo> queryList(AppVersionBo bo) {
        LambdaQueryWrapper<AppVersion> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppVersion> buildQueryWrapper(AppVersionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppVersion> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getAppId() != null, AppVersion::getAppId, bo.getAppId());
        lqw.eq(bo.getFormVersionId() != null, AppVersion::getFormVersionId, bo.getFormVersionId());
        lqw.eq(StringUtils.isNotBlank(bo.getDeployId()), AppVersion::getDeployId, bo.getDeployId());
        lqw.eq(StringUtils.isNotBlank(bo.getDefId()), AppVersion::getDefId, bo.getDefId());
        return lqw;
    }

    /**
     * 新增事项版本
     */
    @Override
    public Boolean insertByBo(AppVersionBo bo) {
        AppVersion add = BeanUtil.toBean(bo, AppVersion.class);
        FormVersionVo formVersionVo = formVersionMapper.selectVoById(bo.getFormVersionId());
        if (formVersionVo != null){
            add.setFormId(formVersionVo.getFormId());
        }
        validEntityBeforeSave(add);
        Long max = baseMapper.selectMaxVersionByAppId(add.getAppId());
        if (max == null) max = 0L;
        add.setVersion(max + 1);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setVersionId(add.getVersionId());
        }
        return flag;
    }

    /**
     * 修改事项版本
     */
    @Override
    public Boolean updateByBo(AppVersionBo bo) {
        AppVersion update = BeanUtil.toBean(bo, AppVersion.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppVersion entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除事项版本
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 部署流程
     *
     * @param appVersionId 事项版本主键
     * @return 结果
     */
    @Override
    public void deployBpmn(Long appVersionId) {
        AppVersionVo appVersion = baseMapper.selectVoById(appVersionId);
        if (appVersion == null) {
            throw new ServiceException("版本不存在或已被删除");
        }
        if (!StringUtils.isEmpty(appVersion.getDeployId())) {
            throw new ServiceException("该流程图已经部署过了");
        }
        AppVo app = appMapper.selectVoById(appVersion.getAppId());

        try {
            Deployment deployment = flowableUtil.deploy(app, appVersion.getBpmnXml());
            appVersion.setDeployId(deployment.getId());
            ProcessDefinition processDefinition = flowableUtil.getDefinByDeployId(deployment.getId());
            appVersion.setDefId(processDefinition.getId());
            AppVersion update = BeanUtil.toBean(appVersion, AppVersion.class);
            baseMapper.updateById(update);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 复制版本
     *
     * @param appVersionId 事项版本主键
     * @return 结果
     */
    @Override
    @Transactional
    public Boolean copyVersion(Long appVersionId) {
        AppVersion appVersion = baseMapper.selectById(appVersionId);
        Long max = baseMapper.selectMaxVersionByAppId(appVersion.getAppId());
        appVersion.setVersion(max + 1);
        appVersion.setCreateTime(DateUtils.getNowDate());
        appVersion.setVersionId(null);
        appVersion.setDeployId(null);
        appVersion.setDefId(null);
        int res = baseMapper.insert(appVersion);
        if (res > 0){
            //复制bpmn配置
            BpmnConfigVo bpmnConfig = bpmnConfigService.selectBpmnConfigByAppVersionId(appVersionId);
            if (bpmnConfig != null){
                bpmnConfig.setAppVersionId(appVersion.getVersionId());
                bpmnConfig.setConfigId(null);
                BpmnConfigBo add = BeanUtil.toBean(bpmnConfig, BpmnConfigBo.class);
                return bpmnConfigService.insertByBo(add);
            }
        }
        return false;
    }

    /**
     * 设置app的当前使用版本
     *
     * @param appVersionId 事项版本主键
     * @return 结果
     */
    @Override
    public int setUseVersion(Long appVersionId) {
        AppVersion appVersion = baseMapper.selectById(appVersionId);
        App app = new App();
        app.setAppId(appVersion.getAppId());
        app.setUseVersion(appVersionId);
        return appMapper.updateById(app);

    }


}
